<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>网吧座位管理</title>
  <!-- 继承原有样式 -->
  <link rel="stylesheet" href="../../css/vertical-layout-light/style.css">
  <!-- 引入本地 Bootstrap CSS -->
  <link rel="stylesheet" href="bootstrap.min.css">
  <style>
    .seat-map-container {
      position: relative;
      width: 100%;
      height: 600px;
      background: transparent; /* 隐藏背景 */
      border: 2px solid #ddd; /* 显示边框 */
      margin: 20px 0;
    }
    .seat-item {
      position: absolute;
      cursor: move;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      transition: left 0.3s ease, top 0.3s ease; /* 优化拖动动画 */
    }
    .single-seat {
      width: 100px;
      height: 60px;
      background: #4CAF50;
      border-radius: 4px;
    }
    .seat-number {
      color: white;
      font-weight: bold;
      margin-bottom: 4px;
    }
    .edit-btn {
      padding: 2px 8px;
      font-size: 12px;
      border-radius: 3px;
    }
    .snap-point {
      position: absolute;
      width: 12px; /* 吸附点的宽度 */
      height: 12px; /* 吸附点的高度 */
      background: red; /* 吸附点的颜色 */
      border: 2px solid yellow; /* 添加边框以增强可见性 */
      border-radius: 50%; /* 使其成为圆形 */
      pointer-events: none; /* 确保吸附点不干扰鼠标事件 */
    }
    .flash {
      animation: flash-animation 0.5s ease-in-out;
    }
    @keyframes flash-animation {
      0% { opacity: 1; }
      50% { opacity: 0.5; }
      100% { opacity: 1; }
    }
  </style>
</head>
<body>
  <div class="container-scroller">
    <!-- 继承原有导航栏 -->
    <!-- partial:../../partials/_navbar.html -->

    <div class="container-fluid page-body-wrapper">
      <!-- 主内容区 -->
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="row">
            <div class="col-12">
              <h4 class="card-title">网吧座位布局编辑器</h4>
              <button id="addSingleSeat" class="btn btn-success ms-2">添加单人座</button>
              <div class="seat-map-container" id="seatMap"></div>
              
              <!-- 编辑模态框 -->
              <div class="modal fade" id="editModal">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title">座位设置</h5>
                    </div>
                    <div class="modal-body">
                      <div class="form-group">
                        <label>座位编号</label>
                        <input type="text" class="form-control" id="seatNumber">
                      </div>
                      <div class="form-group">
                        <label>设备状态</label>
                        <select class="form-control" id="seatStatus">
                          <option value="online">在线</option>
                          <option value="offline">离线</option>
                          <option value="maintenance">维修中</option>
                        </select>
                      </div>
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                      <button type="button" class="btn btn-primary" id="saveChanges">保存</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 引入本地 jQuery 和 Bootstrap JS -->
  <script src="jquery-3.7.1.min.js"></script>
  <script src="bootstrap.min.js"></script>

  <script>
    class SeatManager {
      constructor() {
        this.seats = []; // 默认设置为0个座位
        this.currentSeat = null;
        this.init();
        this.nextId = 1; // 从1开始
        this.gridSize = 100; // 网格大小与图标大小相同
      }

      init() {
        this.renderSeats();
        this.createSnapPoints();
        this.setupEventListeners();
      }

      renderSeats() {
        const container = document.getElementById('seatMap');
        container.innerHTML = '';
        
        this.seats.forEach(seat => {
          const seatEl = document.createElement('div');
          seatEl.className = `seat-item ${seat.status} ${seat.type}`;
          seatEl.style.left = `${seat.x}px`;
          seatEl.style.top = `${seat.y}px`;
          seatEl.innerHTML = `
            <i class="mdi mdi-close-circle delete-seat" style="position: absolute; left: 0; top: 0; color: red; cursor: pointer; font-size: 16px;" data-id="${seat.id}"></i>
            <span class="seat-number">${seat.number}</span>
            <button class="btn btn-light edit-btn" data-id="${seat.id}">编辑</button>
          `;
          container.appendChild(seatEl);
        });
      }

      setupEventListeners() {
        // 拖动功能
        let isDragging = false;
        let currentSeatEl = null;
        let startX, startY, initialX, initialY;

        document.getElementById('seatMap').addEventListener('mousedown', e => {
          if (e.target.classList.contains('seat-item')) {
            isDragging = true;
            currentSeatEl = e.target;
            startX = e.clientX;
            startY = e.clientY;
            initialX = currentSeatEl.offsetLeft;
            initialY = currentSeatEl.offsetTop;
          }
        });

        document.addEventListener('mousemove', e => {
          if (!isDragging) return;
          const dx = e.clientX - startX;
          const dy = e.clientY - startY;
          const newX = initialX + dx;
          const newY = initialY + dy;
          const container = document.getElementById('seatMap');
          const maxX = container.offsetWidth - currentSeatEl.offsetWidth;
          const maxY = container.offsetHeight - currentSeatEl.offsetHeight;
          currentSeatEl.style.left = `${Math.max(0, Math.min(newX, maxX))}px`;
          currentSeatEl.style.top = `${Math.max(0, Math.min(newY, maxY))}px`;
        });

        document.addEventListener('mouseup', () => {
          if (!isDragging) return;
          isDragging = false;
          const seatId = parseInt(currentSeatEl.querySelector('button').dataset.id);
          const seat = this.seats.find(s => s.id === seatId);
          
          // 对齐到最近的网格中心
          seat.x = Math.round((currentSeatEl.offsetLeft + (this.gridSize / 2)) / this.gridSize) * this.gridSize - (this.gridSize / 2);
          seat.y = Math.round((currentSeatEl.offsetTop + (this.gridSize / 2)) / this.gridSize) * this.gridSize - (this.gridSize / 2);
          
          // 检查是否与其他座位重叠
          if (!this.isOverlapping(seat)) {
            currentSeatEl.style.left = `${seat.x}px`;
            currentSeatEl.style.top = `${seat.y}px`;
            this.saveToLocalStorage();
          } else {
            // 如果重叠，恢复到原位置
            currentSeatEl.style.left = `${initialX}px`;
            currentSeatEl.style.top = `${initialY}px`;
          }
        });

        // 编辑功能
        document.getElementById('seatMap').addEventListener('click', e => {
          if (e.target.classList.contains('edit-btn')) {
            const seatId = parseInt(e.target.dataset.id);
            this.currentSeat = this.seats.find(s => s.id === seatId);
            this.showEditModal();
          } else if (e.target.classList.contains('delete-seat')) {
            const seatId = parseInt(e.target.dataset.id);
            this.removeSeat(seatId);
          }
        });

        document.getElementById('saveChanges').addEventListener('click', () => {
          this.currentSeat.number = document.getElementById('seatNumber').value;
          this.currentSeat.status = document.getElementById('seatStatus').value;
          this.saveToLocalStorage();
          this.renderSeats();
          bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
        });
      }

      isOverlapping(newSeat) {
        return this.seats.some(seat => {
          return seat.id !== newSeat.id && 
                 newSeat.x < seat.x + this.gridSize &&
                 newSeat.x + this.gridSize > seat.x &&
                 newSeat.y < seat.y + this.gridSize &&
                 newSeat.y + this.gridSize > seat.y;
        });
      }

      showEditModal() {
        document.getElementById('seatNumber').value = this.currentSeat.number;
        document.getElementById('seatStatus').value = this.currentSeat.status;
        new bootstrap.Modal(document.getElementById('editModal')).show();
      }

      addSeat(type) {
        const newSeat = {
          id: this.nextId++,
          number: `A${this.nextId}`,
          status: 'online',
          type: type, // 添加座位类型
          x: 0, // 设置初始位置为 (0, 0)
          y: 0
        };

        // 找到最近的吸附点
        const snapPoints = this.getSnapPoints();
        let closestSnapPoint = null;
        let closestDistance = Infinity;

        snapPoints.forEach(point => {
          const distance = Math.sqrt(Math.pow(point.x - newSeat.x, 2) + Math.pow(point.y - newSeat.y, 2));
          if (distance < closestDistance) {
            closestDistance = distance;
            closestSnapPoint = point;
          }
        });

        // 将新座位吸附到最近的吸附点
        if (closestSnapPoint) {
          newSeat.x = closestSnapPoint.x;
          newSeat.y = closestSnapPoint.y;
        }

        // 检查新座位是否与现有座位重叠
        while (this.isOverlapping(newSeat)) {
          newSeat.x += this.gridSize; // 向右移动
          if (newSeat.x + this.gridSize > document.getElementById('seatMap').offsetWidth) {
            newSeat.x = 0; // 如果超出边界，重置为0
            newSeat.y += this.gridSize; // 向下移动
          }
        }

        this.seats.push(newSeat);
        this.saveToLocalStorage();
        this.renderSeats();

        // 使新增的座位图标闪烁
        const seatEl = document.querySelector(`.seat-item:last-child`);
        seatEl.classList.add('flash');
        setTimeout(() => {
          seatEl.classList.remove('flash');
        }, 500); // 500ms后移除闪烁效果
      }

      getSnapPoints() {
        const snapPoints = [];
        const container = document.getElementById('seatMap');
        const columns = Math.floor(container.offsetWidth / this.gridSize);
        const rows = Math.floor(container.offsetHeight / this.gridSize);

        for (let i = 0; i < columns; i++) {
          for (let j = 0; j < rows; j++) {
            snapPoints.push({
              x: i * this.gridSize + (this.gridSize / 2) - 6, // 吸附点的 x 坐标
              y: j * this.gridSize + (this.gridSize / 2) - 6  // 吸附点的 y 坐标
            });
          }
        }
        return snapPoints;
      }

      removeSeat(seatId) {
        this.seats = this.seats.filter(s => s.id !== seatId);
        this.saveToLocalStorage();
        this.renderSeats();
      }

      saveToLocalStorage() {
        try {
          const data = JSON.stringify(this.seats);
          if (!data) throw new Error('无效的数据');
          localStorage.setItem('seats', data);
        } catch (error) {
          console.error('保存数据失败:', error);
          alert('保存失败，请重试');
        }
      }

      createSnapPoints() {
        const container = document.getElementById('seatMap');
        const columns = Math.floor(container.offsetWidth / this.gridSize);
        const rows = Math.floor(container.offsetHeight / this.gridSize);

        for (let i = 0; i < columns; i++) {
          for (let j = 0; j < rows; j++) {
            const snapPoint = document.createElement('div');
            snapPoint.className = 'snap-point';
            snapPoint.style.position = 'absolute';
            snapPoint.style.width = '12px'; // 吸附点的宽度
            snapPoint.style.height = '12px'; // 吸附点的高度
            snapPoint.style.background = 'red'; // 吸附点的颜色
            snapPoint.style.border = '2px solid yellow'; // 添加边框以增强可见性
            snapPoint.style.borderRadius = '50%'; // 使其成为圆形
            snapPoint.style.left = `${i * this.gridSize + (this.gridSize / 2) - 6}px`; // 吸附点的 x 坐标
            snapPoint.style.top = `${j * this.gridSize + (this.gridSize / 2) - 6}px`; // 吸附点的 y 坐标
            container.appendChild(snapPoint);
          }
        }
      }
    }

    // 初始化座位管理器
    document.addEventListener('DOMContentLoaded', () => {
      const seatManager = new SeatManager();
      document.getElementById('addSingleSeat').addEventListener('click', () => {
        seatManager.addSeat('single-seat');
      });
    });
  </script>
</body>
</html>